//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package ciicos.alarm.service.impl;

import ciicos.alarm.entity.AlarmRealNDataEntity;
import ciicos.alarm.mapper.AlarmRealNDataMapper;
import ciicos.alarm.model.alarmrealndata.AlarmRealNDataForm;
import ciicos.alarm.model.alarmrealndata.AlarmRealNDataPagination;
import ciicos.alarm.service.AlarmRealNDataService;
import ciicos.base.ActionResult;
import ciicos.base.UserInfo;
import ciicos.base.model.filter.RuleInfo;
import ciicos.base.service.SysconfigService;
import ciicos.config.ConfigValueUtil;
import ciicos.message.controller.SendMessageConfigController;
import ciicos.message.model.messagetemplateconfig.TemplateParamModel;
import ciicos.message.model.sendmessageconfig.SendConfigTemplateModel;
import ciicos.message.util.TestSendConfigUtil;
import ciicos.model.BaseSystemInfo;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.service.UserService;
import ciicos.permission.util.GenUtil;
import ciicos.service.LoginService;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.ServletUtil;
import ciicos.util.StringUtil;
import ciicos.util.TenantUtil;
import ciicos.util.UserProvider;
import ciicos.util.context.SpringContext;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AlarmRealNDataServiceImpl extends ServiceImpl<AlarmRealNDataMapper, AlarmRealNDataEntity> implements AlarmRealNDataService {
    private static final Logger log = LoggerFactory.getLogger(AlarmRealNDataServiceImpl.class);
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    protected ConfigValueUtil configValueUtil;
    @Autowired
    protected LoginService loginService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysconfigService sysConfigApi;
    @Autowired
    private TenantUtil tenantUtil;
    @Autowired
    private TestSendConfigUtil testSendConfigUtil;
    @Value("${messageTemplate.alarm}")
    private String templateId;

    @Override
    public List<AlarmRealNDataEntity> getList(AlarmRealNDataPagination alarmRealNDataPagination) {
        return this.getTypeList(alarmRealNDataPagination, alarmRealNDataPagination.getDataType());
    }

    @Override
    public List<AlarmRealNDataEntity> getTypeList(AlarmRealNDataPagination alarmRealNDataPagination, String dataType) {
        String userId = this.userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList();
        int total = 0;
        int alarmRealNDataNum = 0;
        QueryWrapper<AlarmRealNDataEntity> alarmRealNDataQueryWrapper = new QueryWrapper();
        List<String> allSuperIDlist = new ArrayList();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(alarmRealNDataPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = (SuperQueryJsonModel)JsonUtil.getJsonToBean(alarmRealNDataPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);

            for(ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null && Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                    conditionjson.setFieldValue("[]");
                }

                conditionjson.setTableName(tableName);
            }

            List<String> allSuperList = new ArrayList();
            List<List<String>> intersectionSuperList = new ArrayList();
            int alarmRealNDataNum1 = 0;
            QueryWrapper<AlarmRealNDataEntity> alarmRealNDataSuperWrapper = new QueryWrapper();
            alarmRealNDataNum1 = this.generaterSwapUtil.getCondition(new SuperQueryConditionModel(alarmRealNDataSuperWrapper, superQueryList, matchLogic, "alarm_real_n_data"), new AlarmRealNDataEntity(), alarmRealNDataNum1);
            if (alarmRealNDataNum1 > 0) {
                List<String> alarmRealNDataList = (List)this.list(alarmRealNDataSuperWrapper).stream().map(AlarmRealNDataEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(alarmRealNDataList);
                intersectionSuperList.add(alarmRealNDataList);
            }

            superOp = matchLogic;
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = this.generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }

        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission && !this.userProvider.get().getIsAdministrator()) {
            Object alarmRealNDataObj = this.authorizeService.getCondition(new AuthorizeConditionModel(alarmRealNDataQueryWrapper, alarmRealNDataPagination.getMenuId(), "alarm_real_n_data"));
            if (ObjectUtil.isEmpty(alarmRealNDataObj)) {
                return new ArrayList();
            }

            alarmRealNDataQueryWrapper = (QueryWrapper)alarmRealNDataObj;
            if (alarmRealNDataQueryWrapper.getExpression().getNormal().size() > 0) {
                ++alarmRealNDataNum;
            }
        }

        if (!isPc && appPermission && !this.userProvider.get().getIsAdministrator()) {
            Object alarmRealNDataObj = this.authorizeService.getCondition(new AuthorizeConditionModel(alarmRealNDataQueryWrapper, alarmRealNDataPagination.getMenuId(), "alarm_real_n_data"));
            if (ObjectUtil.isEmpty(alarmRealNDataObj)) {
                return new ArrayList();
            }

            alarmRealNDataQueryWrapper = (QueryWrapper)alarmRealNDataObj;
            if (alarmRealNDataQueryWrapper.getExpression().getNormal().size() > 0) {
                ++alarmRealNDataNum;
            }
        }

        if (!this.userProvider.get().getIsAdministrator()) {
            if (alarmRealNDataPagination.getArerList() != null && alarmRealNDataPagination.getArerList().size() > 0) {
                ++alarmRealNDataNum;
                alarmRealNDataQueryWrapper.lambda().in(AlarmRealNDataEntity::getTagarea, alarmRealNDataPagination.getArerList());
            }
        } else if (ObjectUtil.isNotEmpty(alarmRealNDataPagination.getTagarea())) {
            ++alarmRealNDataNum;
            alarmRealNDataQueryWrapper.lambda().like(AlarmRealNDataEntity::getTagarea, alarmRealNDataPagination.getTagarea());
        }

        if (ObjectUtil.isNotEmpty(alarmRealNDataPagination.getTagname())) {
            ++alarmRealNDataNum;
            alarmRealNDataQueryWrapper.lambda().like(AlarmRealNDataEntity::getTagname, alarmRealNDataPagination.getTagname());
        }

        if (ObjectUtil.isNotEmpty(alarmRealNDataPagination.getEnabledmark())) {
            ++alarmRealNDataNum;
            alarmRealNDataQueryWrapper.lambda().eq(AlarmRealNDataEntity::getEnabledmark, alarmRealNDataPagination.getEnabledmark());
        }

        if (ObjectUtil.isNotEmpty(alarmRealNDataPagination.getAlarmtype())) {
            ++alarmRealNDataNum;
            List<String> idList = new ArrayList();

            try {
                String[][] alarmtype = (String[][])JsonUtil.getJsonToBean(alarmRealNDataPagination.getAlarmtype(), String[][].class);

                for(int i = 0; i < alarmtype.length; ++i) {
                    if (alarmtype[i].length > 0) {
                        idList.add(alarmtype[i][alarmtype[i].length - 1]);
                    }
                }
            } catch (Exception var21) {
                try {
                    List<String> alarmtype = JsonUtil.getJsonToList(alarmRealNDataPagination.getAlarmtype(), String.class);
                    if (alarmtype.size() > 0) {
                        idList.add(alarmtype.get(alarmtype.size() - 1));
                    }
                } catch (Exception var20) {
                    idList.add(String.valueOf(alarmRealNDataPagination.getAlarmtype()));
                }
            }

            alarmRealNDataQueryWrapper.lambda().and((t) -> idList.forEach((tt) -> ((LambdaQueryWrapper)t.like(AlarmRealNDataEntity::getAlarmtype, tt)).or()));
        }

        List<String> intersection = this.generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }

            alarmRealNDataQueryWrapper.lambda().in(AlarmRealNDataEntity::getId, intersection);
        }

        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            alarmRealNDataQueryWrapper.lambda().and(t->t.in(AlarmRealNDataEntity::getId, finalAllSuperIDlist));
        }

        if (StringUtil.isEmpty(alarmRealNDataPagination.getSidx())) {
            alarmRealNDataQueryWrapper.lambda().orderByDesc(AlarmRealNDataEntity::getId);
        } else {
            try {
                String sidx = alarmRealNDataPagination.getSidx();
                AlarmRealNDataEntity alarmRealNDataEntity = new AlarmRealNDataEntity();
                Field declaredField = alarmRealNDataEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                alarmRealNDataQueryWrapper = "asc".equals(alarmRealNDataPagination.getSort().toLowerCase()) ? alarmRealNDataQueryWrapper.orderByAsc(value) : alarmRealNDataQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if (!"0".equals(dataType)) {
            return this.list(alarmRealNDataQueryWrapper);
        } else if ((total <= 0 || AllIdList.size() <= 0) && total != 0) {
            List<AlarmRealNDataEntity> list = new ArrayList();
            return alarmRealNDataPagination.setData(list, list.size());
        } else {
            Page<AlarmRealNDataEntity> page = new Page(alarmRealNDataPagination.getCurrentPage(), alarmRealNDataPagination.getPageSize());
            IPage<AlarmRealNDataEntity> userIPage = this.page(page, alarmRealNDataQueryWrapper);
            return alarmRealNDataPagination.setData(userIPage.getRecords(), userIPage.getTotal());
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            wrapper.apply(" 1=1 ", new Object[0]);

            for(RuleInfo info : this.generaterSwapUtil.getFilterCondition(id)) {
                String field = info.getField();
                if ((!"main".equals(type) || !field.contains("-")) && (!"main".equals(type) || !field.contains("_jnpf_")) && (!"sub".equals(type) || field.contains("-")) && (!"sub-jnpf".equals(type) || field.contains("_jnpf_"))) {
                    String fieldName = field;
                    String table = "";
                    if (field.contains("-")) {
                        fieldName = field.split("-")[1];
                    }

                    if (field.contains("_jnpf_")) {
                        fieldName = field.split("_jnpf_")[1];
                        table = field.split("_jnpf_")[0];
                        table = table.replace("jnpf_", "");
                    }

                    if (!"sub-jnpf".equals(type) || tableName.equals(table)) {
                        Field declaredField = aClass.getDeclaredField(fieldName);
                        declaredField.setAccessible(true);
                        String fieldDb = declaredField.getAnnotation(TableField.class).value();
                        GenUtil genUtil = JsonUtil.getJsonToBean(info, GenUtil.class);
                        genUtil.solveValue(wrapper, fieldDb);
                    }
                }
            }

            return wrapper;
        } catch (Exception var15) {
            return wrapper;
        }
    }

    @Override
    public AlarmRealNDataEntity getInfo(String id) {
        QueryWrapper<AlarmRealNDataEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(AlarmRealNDataEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(AlarmRealNDataEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, AlarmRealNDataEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(AlarmRealNDataEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }

    }

    @Override
    public String checkForm(AlarmRealNDataForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }

        return countRecover;
    }

    @Override
    public boolean confirm(AlarmRealNDataEntity entity) {
        String userId = this.userProvider.get().getUserId();
        entity.setConfirm(1);
        entity.setLastmodifyuserid(userId);
        entity.setLastmodifytime(new Date());
        return this.updateById(entity);
    }

    @Override
    public void doSendMessage(String id, String tenant) {
        UserInfo userInfo = this.userProvider.get();
        if (StringUtil.isNotEmpty(tenant)) {
            userInfo.setUserAccount(tenant + "@admin");
        } else {
            userInfo.setUserAccount("admin");
        }

        this.tenantUtil.switchTenant(userInfo);
        AlarmRealNDataEntity info = this.getInfo(id);
        if (null == info) {
            log.info("【报警消息】实时报警数据不存在");
        } else {
            BaseSystemInfo sysInfo = this.sysConfigApi.getSysInfo();
            String scadaAlarmUser = sysInfo.getScadaAlarmUser();
            String[] scadaAlarmUsers = scadaAlarmUser.split(",");
            if (null != scadaAlarmUsers && scadaAlarmUsers.length != 0) {
                List<String> scadaAlarmUserList = Arrays.asList(scadaAlarmUsers);
                List<String> userIdList = this.userService.getUserIdList(scadaAlarmUserList);
                ActionResult<List<SendConfigTemplateModel>> testConfig = ((SendMessageConfigController)SpringContext.getBean(SendMessageConfigController.class)).getTestConfig(this.templateId);
                if (testConfig.getCode() != 200) {
                    log.info("【报警消息】获取发送消息-配置失败");
                } else {
                    List<SendConfigTemplateModel> configTemplateModelList = (List)testConfig.getData();
                    if (null == configTemplateModelList && configTemplateModelList.size() == 0) {
                        log.info("【报警消息】获取发送消息-模板失败");
                    } else {
                        for(SendConfigTemplateModel model : configTemplateModelList) {
                            Map<String, Object> map = JsonUtil.entityToMap(info);
                            List<TemplateParamModel> paramModels = new ArrayList();

                            for(Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
                                String key = (String)stringObjectEntry.getKey();
                                TemplateParamModel templateParamModel = new TemplateParamModel();
                                templateParamModel.setId(model.getId());
                                templateParamModel.setTemplateType(model.getMessageType());
                                templateParamModel.setTemplateId(model.getTemplateId());
                                templateParamModel.setField(key);
                                templateParamModel.setValue(map.get(key) + "");
                                paramModels.add(templateParamModel);
                            }

                            model.setToUser(userIdList);
                            model.setParamJson(paramModels);
                        }

                        log.info("【报警消息】获取发送消息-发送参数 {}", configTemplateModelList);
                        if (configTemplateModelList != null && configTemplateModelList.size() > 0) {
                            for(SendConfigTemplateModel model : configTemplateModelList) {
                                String result = this.testSendConfigUtil.sendMessage(model, userInfo);
                                if (StringUtil.isEmpty(result)) {
                                    info.setSendmark(1);
                                    this.update(id, info);
                                } else {
                                    log.info("【报警消息】获取发送消息-返回结果 {}", result);
                                }
                            }
                        }

                    }
                }
            } else {
                log.info("【报警消息】报警接收人不存在");
            }
        }
    }
}
